<template>
  <div class="add-group">
    <transition name="van-slide-right">
      <div class="add-group-main" v-show="isSelect">
        <ul class="add-group-from">
          <li class="item-info">
            <p class="title">分组名称</p>
            <div class="content">
              <input type="text" v-model="groupName" maxlength="6" placeholder="请设置分组名称" >
            </div>
          </li>
          <li class="item-info">
            <p class="title">客户{{ selectCustom.length }}</p>
            <div class="avatar-list" @click="isEdit = false">
              <div class="avatar-size" v-for="(item, index) in selectCustom" @click.stop="removeHandle(index)">
                <span class="image avatar":style="{ backgroundImage: `url(${item.avatarUrl})` }"></span>
                <span v-show="isEdit" class="remove iconfont icon-search_empty"></span>
                <span class="text ellipsis">{{ item.clientRemarkName }}</span>
              </div>
              <div class="avatar-size plus"
                :style="{ visibility: !isEdit ? 'visible' : 'hidden' }"
                @click.stop="addGroupUser">
                <i class="iconfont icon-tianjia"></i>
              </div>
              <div class="avatar-size reduce"
                :style="{ visibility: !isEdit ? 'visible' : 'hidden' }"
                v-show="selectCustom.length"
                @click.stop="isEdit = true"
              >
                <i class="iconfont icon-shanjian"></i>
              </div>
            </div>
          </li>
        </ul>
        <div class="footer-botton van-hairline--top">
          <span class="gray" @click="cancel">取消</span>
          <span class="blue" @click="complete">完成</span>
        </div>
      </div>
    </transition>
    <transition name="van-slide-right">
      <div class="address-select" v-show="!isSelect">
        <div class="search van-hairline--bottom" ref="selectList">
          <div class="select-list">
            <span class="image image-size" v-for="item in selectCustom" :style="{ backgroundImage: `url(${item.avatarUrl})` }"></span>
            <input type="text" v-model="searchValue" placeholder="搜索" @input="inputChang" />
          </div>
        </div>
        <index-bar id="Bscroll" :shortcutList="shortcutList" :singers="customerList" :isTrigger="isLoading" ref="indexBar">
          <div slot="upper">
            <div class="loading" v-show="!isLoading" >
              <van-loading size="50px" />
            </div>
          </div>
          <div slot-scope="props">
            <h2 class="list-group-title">{{ props.title }}</h2>
            <van-checkbox-group v-model="selectValues">
              <ul>
                <li v-for="(item, index) in props.items" class="list-group-item van-hairline--bottom" :key="item.clientId" @click="toggle(item)">
                  <van-checkbox ref="checkboxes" :key="item.clientId" :name="item.clientId" :disabled="!!item.disabled"></van-checkbox>
                  <img v-lazy="item.avatarUrl" class="avatar">
                  <span class="name">{{ item.clientRemarkName }}</span>
                </li>
                <li v-if="props.current < props.pages" class="next" @click="getNextPage(props.title, props.current)">查看更多</li>
              </ul>
            </van-checkbox-group>
          </div>
        </index-bar>
        <div class="footer-botton van-hairline--top">
          <span class="gray" @click="cancel">取消</span>
          <span class="blue" @click="complete">完成</span>
        </div>
      </div>
    </transition>
    <div class="search-view" v-if="searchValue">
      <van-checkbox-group v-if="searchList.length || !searchLoading" v-model="selectValues">
        <ul>
          <li v-for="(item, index) in searchList" class="list-group-item van-hairline--bottom" :key="item.clientId" @click="toggle(item, true)">
            <span @click.stop><van-checkbox ref="checkboxes" :key="item.clientId" :name="item.clientId" :disabled="!!item.disabled"></van-checkbox></span>
            <img v-lazy="item.avatarUrl" class="avatar">
            <span class="name">{{ item.clientRemarkName }}</span>
          </li>
        </ul>
      </van-checkbox-group>
      <div class="no-data" v-else>
        <img src="@/assets/img/article/empty_article@2x.png"alt="">
        <p>暂无搜索内容</p>
      </div>
    </div>
  </div>
</template>

<script>
// import singers from './testData'
import { debounce, isEmpty } from 'lodash'
import indexBar from '@/components/indexBar'
import customService  from '@/services/customService'
let size = 20

export default {
  data() {
    return {
      customerList: [],
      isSelect: false,
      isEdit: false,
      isAdd: false,
      isLoading: false,
      searchLoading: false,
      groupName: '',
      searchValue: '',
      selectCustom: [],
      selectValues: [],
      searchList: [],
      shortcutList: []
    }
  },
  components: {
    indexBar
  },
  created() {
    let { classifyId, groupName } = this.$route.query
    if (!classifyId) {
      this.getAllCustomer()
    } else {
      this.groupName = groupName
      this.classifyId= classifyId
      document.title = '编辑分组'
      this.getGroupList()
    }
  },
  watch: {
    selectValues(newVal, oldVal) {
      if (this.isEdit) return false
      // 获取选中前的数组和选中后的数组做对比，取差集
      // 获取选中当前项或者取消当前项的id
      let value = oldVal.concat(newVal).filter(v => !oldVal.includes(v) || !newVal.includes(v))
      // 选中项减少
      if ( oldVal.length > newVal.length ) {
        this.selectChange(value, false)
      } else {
        this.selectChange(value, true)
      }
    }
  },
  methods: {
     async getAllCustomer() {
      let res = await customService.getAllCustomerList({ total: size, real: true })
      this.shortcutList = res.map(group => group.initial)
      this.customerList = res
      this.isLoading = true
    },
    async getNextPage(initial, current) {
      let res = await customService.getMoreCustomerList({ initial, size: size, real: true, current: current+1 })
      this.customerList.some(group => {
        if (group.initial === initial) {
          group.page.current = res.current
          group.page.records = group.page.records.concat(res.records)
          return true
        }
      })
      this.$nextTick(() => {
        this.$refs.indexBar._calculateHeight()
      })
    },
    async getGroupList() {
      this.isSelect = true
      let res = await customService.getCustomerList({ current: 1, size: 1000, classifyId: this.classifyId })
      this.selectCustom = res.records
      let selects = res.records.map(item => item.clientId)
      this.selectValues = selects
      this.selectCustomBak = selects
      await this.getAllCustomer()
      let selectCustom = []
      this.customerList.forEach(group => {
        group.page.records.forEach(item => {
          if (selects.includes(item.clientId)) {
            item.disabled = true
            selectCustom.push(item)
          }
        })
      })
      this.selectCustom = selects.map(item => {
        return selectCustom.find(current => current.clientId === item )
      })
    },
    selectChange(values, bool) {
      let id = values[values.length - 1]
      this.customerList.some(list => {
        return list.page.records.some((item, index) => {
          if (id === item.clientId) {
            if (bool) {
              this.selectCustom.push(item)
            } else {
              let int = this.selectCustom.findIndex(item => item.clientId === id )
              this.selectCustom.splice(int, 1)
            }
            return true
          }
        })
      })
      if (bool) this.scrollMove()
    },
    scrollMove() {
      this.$nextTick(() => {
        let element = this.$refs.selectList
        let scroll = element.scrollWidth - document.body.clientWidth
        if (scroll > 0) {
          element.scrollLeft = scroll
        }
      })
    },
    toggle(item, isBack) {
      if (item.disabled) return false
      // let selectValues = this.selectValues
      this.$refs.checkboxes.some(group => {
        if (group.name === item.clientId) {
          group.toggle()
          return true
        }
      })
      if (isBack) {
        setTimeout(() => {
          this.searchValue = ''
        }, 300)
      }
    },
    removeHandle(index) {
      if (this.isEdit) {
        this.selectCustom.some((item, int) => {
          if (index === int ) {
            item.disabled = false
            this.selectCustom.splice(index, 1)
          }
        })
        if (!this.selectCustom.length) {
          this.isEdit = false
        }
        this.selectValues = this.selectCustom.map(item => item.clientId)
      }
    },
    addGroupUser() {
      this.isSelect = false
      this.selectCustom.forEach(item => {
        item.disabled = true
      })
    },
    inputChang: debounce(function(){
      this.searchList = []
      this.searchLoading = false
      this.searchCustom()
    }, 500),
    async searchCustom() {
      if (!this.searchValue) return false
      let res = await customService.getAllCustomerList({ total: size, real: true, searchName: this.searchValue })
      let searchList = []
      res.forEach(group => {
        group.page.records.forEach(item => {
          searchList.push(item)
        })
      })
      searchList.forEach(item => {
        if (this.selectValues.includes(item.clientId)) {
          let current = this.selectCustom.find(page => page.clientId === item.clientId)
          item.disabled = current.disabled || false
        }
      })
      this.searchList = searchList
      this.searchLoading = true
    },
    async savaUpdateGroup() {
      try {
        let obj = {
          classifyId: this.classifyId || '',
          clientIds: this.selectCustom.map(item => item.clientId),
          title: this.groupName
        }
        if (this.selectCustomBak) {
          let delClientIds = this.selectCustomBak.filter(item => !this.selectValues.includes(item))
          if (delClientIds && delClientIds.length) {
            obj.delClientIds = delClientIds
          }
        }
        let res = await customService.updateCustomerGroup(obj)
        this.$toast.success("保存成功")
        setTimeout(() => {
          this.$router.go(-1)
        }, 300)
      } catch (error) {
        console.log(error)
      }
    },
    complete() {
      if (!this.isSelect) {
        if (!this.selectCustom.length) {
          this.$toast("请选择加入分组的用户")
          return false
        }
        this.isSelect = true
      } else {
        // 保存新建分组
        if (!this.groupName) {
          this.$toast("请输入分组名称")
          return false
        } else if (!this.selectCustom.length) {
          this.$toast("请选择添加分组的用户")
          return false
        }
        this.savaUpdateGroup()
      }
    },
    cancel() {
      this.$router.go(-1)
      // if (this.isSelect) {
      //   this.isSelect = false
      // } else {
      //   this.$router.go(-1)
      // }
    }
  }
} 
</script>

<style lang="less" scoped>

.add-group {
  background: #F7F9FA;
  .add-group-main {
    height: 100%;
  }
  .add-group-from {
    height: calc(100% - 60px);

    .item-info {
      .title {
        color: #405170;
        font-size: 12px;
        line-height: 16px;
        padding: 20px 16px 8px 16px;
      }

      .content {
        height: 52px;
        background: #fff;
        padding: 0 16px;
        font-size: 16px;
        display: flex;
        align-items: center;
        input {
          border: 0px;
          color: #9BA4B4;
        }
        i {
          color: #007AE6;
        }
        span {
          padding-left: 4px;
          color: #13284D;
        }
      }
      .avatar-list {
        padding: 12px 16px;
        background: #fff;
        overflow: hidden;
        .avatar-size {
          width: 40px;
          text-align: center;
          float: left;
          margin-right: 20px;
          margin-bottom: 16px;
          position: relative;
          &:nth-child(6n) {
            margin-right: 0;
          }
          .avatar {
            width: 100%;
            height: 40px;
            display: block;
          }
          .text {
            display: block;
            color: #9BA4B4;
            font-size: 12px;
            line-height: 16px;
            padding-top: 4px;
          }
          .remove {
            position: absolute;
            top: 0;
            right: -6px;
            color: #EA4D2E;
          }
          i {
            font-size: 40px;
          }
        }
        .plus, .reduce{
          height: 40px;
          // border: 1px solid #DBDEE4;
          border-radius: 50%;
          color: #DBDEE4;
        }
      }
    }
  }

.ellipsis {
  overflow: hidden;
  text-overflow: ellipsis;
  -o-text-overflow: ellipsis;
  white-space: nowrap;
}

.image { 
  display: inline-block;
  background-position: center;
  background-repeat: no-repeat;
  background-size: contain;
  border-radius: 50%;
}

.address-select {
  height: 100%;
  background: #fff;
}

  .search {
    width: 100%;
    height: 56px;
    padding: 10px 16px;
    overflow-y: scroll;
    &::-webkit-scrollbar {
      display:none;
    }
   .select-list {
      white-space: nowrap;
      height: 36px;
      line-height: 36px;
      .image-size {
        width: 36px;
        height: 36px;
        margin-right: 4px;
        vertical-align: bottom;
      }
      
      input {
        border: 0;
        font-size: 14px;
        color: #9CA5B5;
        line-height: 24px;
        margin-left: 4px;
        max-width: 120px;
        vertical-align: text-bottom;
      }
   }
  }

  #Bscroll {
    height: calc(100% - 116px);
    .loading {
      display: flex;
      align-items: center;
      justify-content: center;
      height: 500px;
    }
  }
  .list-group-title {
    height: 32px;
    line-height: 32px;
    padding-left: 16px;
    font-size: 12px;
    color: #405170;
    background: #F7F9FA;
  }
  .list-group-item {
    display: flex;
    align-items: center;
    padding: 10px 16px;
    .avatar {
      width: 36px;
      height: 36px;
      border-radius: 50%;
    }
    .item-info {
      padding-left: 16px;
    }
    .name {
      margin-left: 20px;
      line-height: 24px;
      color: #13284D;
      font-size: 14px;
    }
    .tips {
      line-height: 16px;
      color: #9BA4B4;
      font-size: 12px;
    }
    /deep/ .van-checkbox__icon {
      vertical-align: baseline;
      padding-right: 8px;
    }
  }
  .next {
    font-size: 14px;
    text-align: center;
    padding: 12px 0;
  }

  .footer-botton {
    height: 60px;
    width: 100%;
    padding: 8px 16px;
    background: #fff;
    font-size: 16px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    span {
      width: 164px;
      height: 44px;
      align-self: center;
      line-height: 44px;
      text-align: center;
      border-radius: 6px;
    }
    .gray {
      color: #445166;
      background: #E3E9EF;
    }
    .blue {
      color: #fff;
      background: #007AE6;
    }
  }
  
  .search-view {
    width: 100%;
    height: calc(100% - 56px);
    position: fixed;
    top: 56px;
    z-index: 100;
    background: #fff;
  }
  .no-data {
    font-size: 12px;
    text-align: center;
    margin-top: 200px;
    color: #999;
    img {
      width: 88px;
      height: 88px;
    }
  }

}


</style>